package com.wm.web.action;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.interceptor.SessionAware;

import com.wm.bean.Address;
import com.wm.bean.OrderMenu;
import com.wm.bean.OrderResMenu;
import com.wm.bean.Orders;
import com.wm.bean.Restaurant;
import com.wm.comm.Constant;
import com.wm.comm.Util;
import com.wm.service.AddressService;
import com.wm.service.OrderResMenuService;
import com.wm.service.OrdersService;
import com.wm.service.RestaurantService;
import com.wm.service.RestaurantTimeService;
import com.wm.web.servlet.UserSession;

public class ShoppingAction extends BaseAction implements SessionAware {
	private static final Log logger = LogFactory.getLog(ShoppingAction.class);
	
	private OrdersService ordersService;
	private OrderResMenuService orderResMenuService;
	private RestaurantService restaurantService;
	private AddressService addressService;

	public AddressService getAddressService() {
		return addressService;
	}

	public void setAddressService(AddressService addressService) {
		this.addressService = addressService;
	}

	public RestaurantService getRestaurantService() {
		return restaurantService;
	}

	public void setRestaurantService(RestaurantService restaurantService) {
		this.restaurantService = restaurantService;
	}

	public OrderResMenuService getOrderResMenuService() {
		return orderResMenuService;
	}

	public void setOrderResMenuService(OrderResMenuService orderResMenuService) {
		this.orderResMenuService = orderResMenuService;
	}

	public OrdersService getOrdersService() {
		return ordersService;
	}

	public void setOrdersService(OrdersService ordersService) {
		this.ordersService = ordersService;
	}

	private Map session;

	public void setSession(Map session) {
		this.session = session;
	}

	public Map getSession() {
		return session;
	}
	
	private String result;
	private long id;
	private Orders orders;
	private long resId;
	private long menuId;
	private int copies;
	private String menuName;
	private int price;
	private String error;
	private String resName;
	private String returnURL;
	private Restaurant restaurant;
	private List AddressList;

	public List getAddressList() {
		return AddressList;
	}

	public void setAddressList(List addressList) {
		AddressList = addressList;
	}

	public Restaurant getRestaurant() {
		return restaurant;
	}

	public void setRestaurant(Restaurant restaurant) {
		this.restaurant = restaurant;
	}

	public String getReturnURL() {
		return returnURL;
	}

	public void setReturnURL(String returnURL) {
		this.returnURL = returnURL;
	}

	public String getResName() {
		return resName;
	}

	public void setResName(String resName) {
		this.resName = resName;
	}

	public int getPrice() {
		return price;
	}

	public void setPrice(int price) {
		this.price = price;
	}

	public String getMenuName() {
		return menuName;
	}

	public void setMenuName(String menuName) {
		this.menuName = menuName;
	}

	public String getError() {
		return error;
	}

	public void setError(String error) {
		this.error = error;
	}

	public long getResId() {
		return resId;
	}

	public void setResId(long resId) {
		this.resId = resId;
	}

	public long getMenuId() {
		return menuId;
	}

	public void setMenuId(long menuId) {
		this.menuId = menuId;
	}

	public int getCopies() {
		return copies;
	}

	public void setCopies(int copies) {
		this.copies = copies;
	}
	
	public String getResult() {
		return result;
	}

	public void setResult(String result) {
		this.result = result;
	}
	
	public Orders getOrders() {
		return orders;
	}

	public void setOrders(Orders orders) {
		this.orders = orders;
	}

	public long getId() {
		return id;
	}

	public void setId(long id) {
		this.id = id;
	}	
	
	public String execute() {
		try {
			return this.executeMethod(this.getAction());
		} catch (Exception e) {
			logger.error(e);
			return INPUT;
		}
	}

	/**
	 * 查询购物车
	 * @return
	 */
	public String index(){
//		if(this.getSession().get(Constant.USER_SESSION_KEY)==null){
//			return "index";
//		}
//		UserSession us = (UserSession)this.getSession().get(Constant.USER_SESSION_KEY);
		//查询购物车
		//this.setOrders(this.getOrdersService().findOrdersByUserIdState(us.getUid(), -1));
		this.setOrders((Orders)this.getSession().get(Constant.SHOPPING_SESSION_KEY));
		if(this.getOrders()!=null){
			long totalPrice = 0;
			int totalCopies = 0;
			Restaurant r = this.getRestaurantService().findRestaurantById(this.getOrders().getResId());
			if(this.getOrders().getMenuList()!=null && this.getOrders().getMenuList().size()>0){
				for(int i=0;i<this.getOrders().getMenuList().size();i++){
					OrderResMenu om = (OrderResMenu)this.getOrders().getMenuList().get(i);
					om.setTotalPrice(om.getPrice()*om.getCopies());
					totalPrice = totalPrice + om.getTotalPrice();
					totalCopies = totalCopies + om.getCopies();
					om.setPriceShow(Util.getPriceShow(om.getPrice()));
					om.setTotalPriceShow(Util.getPriceShow(om.getTotalPrice()));
				}
			}
			this.getOrders().setTotalCopies(totalCopies);
			this.getOrders().setTotalPrice2(totalPrice);
			this.getOrders().setTotalPriceShow((Util.getPriceShow(totalPrice)));
			if(r.getDeliveryPrice()>totalPrice){
				this.getOrders().setDelivery(Util.getPriceShow(r.getDeliveryPrice()-totalPrice));
			}else{
				this.getOrders().setDelivery("0");
			}
		}
		
		
		//获取错误信息
		if(this.getError()!=null&&!this.getError().equals("")){
			this.addFieldError("error", this.getText(this.getError()));
		}
		return "index";
	}
	
	/**
	 * 将购物车下单
	 * @return
	 */
	public String save(){
//		if(this.getSession().get(Constant.USER_SESSION_KEY)==null){
//			this.setReturnURL(Constant.WEB_URL+"shopping.action?action=checkOrder");
//			this.setAction("index");
//			return "loginAction";
//		}
		this.setOrders((Orders)this.getSession().get(Constant.SHOPPING_SESSION_KEY));
		if(this.getOrders()!=null){
			//下单
			this.getOrdersService().saveOrders(this.getOrders());
			if(this.getOrders().getMenuList()!=null && this.getOrders().getMenuList().size()>0){
				for(int i=0;i<this.getOrders().getMenuList().size();i++){
					OrderResMenu orderResMenu = (OrderResMenu)this.getOrders().getMenuList().get(i);
					this.getOrderResMenuService().saveOrderResMenu(orderResMenu);
				}
			}
		}
		return null;
	}
	
	/**
	 * 去下单页
	 * @return
	 */
	public String checkOrder(){
		//返回地址处理
		if(this.getReturnURL()!=null){
			String[] url = this.getReturnURL().split("&error");
			if(url.length>1){
				this.setReturnURL(url[0]);
			}
		}
		//查询购物车
		this.setOrders((Orders)this.getSession().get(Constant.SHOPPING_SESSION_KEY));
		//购物车是空的 返回
		if(this.getOrders()==null){
			this.setReturnURL(this.getReturnURL()+"&error=1");
			return "returnUrl";
		}
		//是否足够起送价
		this.setRestaurant(this.getRestaurantService().findRestaurantById(this.getOrders().getResId()));
		if(this.getOrders().getTotalPrice2()<this.getRestaurant().getDeliveryPrice()){
			this.setReturnURL(this.getReturnURL()+"&error=2");
			return "returnUrl";
		}
		//是否登录
//		if(this.getSession().get(Constant.USER_SESSION_KEY)==null){
//			this.setReturnURL(Constant.WEB_URL+"shopping.action?action=checkOrder");
//			this.setAction("index");
//			return "loginAction";
//		}
		//进入下单页
		long totalPrice = 0;
		int totalCopies = 0;
		Restaurant r = this.getRestaurantService().findRestaurantById(this.getOrders().getResId());
		if(this.getOrders().getMenuList()!=null && this.getOrders().getMenuList().size()>0){
			for(int i=0;i<this.getOrders().getMenuList().size();i++){
				OrderResMenu om = (OrderResMenu)this.getOrders().getMenuList().get(i);
				om.setTotalPrice(om.getPrice()*om.getCopies());
				totalPrice = totalPrice + om.getTotalPrice();
				totalCopies = totalCopies + om.getCopies();
				om.setPriceShow(Util.getPriceShow(om.getPrice()));
				om.setTotalPriceShow(Util.getPriceShow(om.getTotalPrice()));
//				this.getOrderResMenuService().saveOrderResMenu(om);
			}
		}
		UserSession us = (UserSession)this.getSession().get(Constant.USER_SESSION_KEY);
//		Address address = this.getAddressService().findAddressByIsUserIdDefault(us.getUid());
//		this.getOrders().setTotalCopies(totalCopies);
//		this.getOrders().setLinkMan(address.getLinkman());
//		this.getOrders().setPhone(address.getPhone());
//		this.getOrders().setAddress(address.getAddress());
//		if(address.getBackPhone()!=null){
//			this.getOrders().setBackPhone(address.getBackPhone());
//		}
//		this.setAddressList(this.getAddressService().findAddressByUserId(us.getUid()));
		this.getOrders().setTotalPriceShow((Util.getPriceShow(totalPrice)));
//		this.getOrdersService().saveOrders(orders);
		
		return "checkOrder";
	}
	
	/**
	 * 加入购物车
	 * @return
	 */
	public String add(){
		if(resId<1 || menuName==null || copies<1 ){
			this.setError("error.error");
			this.setAction("index");
			return null;
		}
		try { 
			menuName=java.net.URLDecoder.decode(menuName ,"UTF-8");
			resName=java.net.URLDecoder.decode(resName ,"UTF-8");
		} catch (Exception e) {  
		    e.printStackTrace();  
		}
		//购物车的东西在session里
		this.setOrders((Orders)this.getSession().get(Constant.SHOPPING_SESSION_KEY));
		//购物车空的新建信息
		if(this.getOrders()==null){
			Orders o = new Orders();
			o.setResId(resId);
			o.setResName(resName);
			o.setState(-1);
			List menuList = new ArrayList();
			OrderResMenu orm = new OrderResMenu();
			orm.setOrderId(resId);
			orm.setMenuName(menuName);
			orm.setPrice(price);
			orm.setCopies(1);
			menuList.add(orm);
			o.setMenuList(menuList);
			this.getSession().put(Constant.SHOPPING_SESSION_KEY, o);
			this.setAction("index");
			return null;
		}
		//已有但不是同一家店 提示
		if(this.getOrders().getResId()!=this.getResId()){
			this.setError("error.entity.error");
			this.setAction("index");
			return null;
		}
		//已有而且是同一家店 更新
		List menuList = new ArrayList();
		//如果菜单是空的
		if(this.getOrders().getMenuList()==null || this.getOrders().getMenuList().size()==0){
			OrderResMenu orm = new OrderResMenu();
			orm.setOrderId(resId);
			orm.setMenuName(menuName);
			orm.setPrice(price);
			orm.setCopies(copies);
			menuList = new ArrayList();
			menuList.add(orm);
			this.getOrders().setMenuList(menuList);
		}
		//如果不是空的
		else{
			Boolean bl = true;
			for(int i=0;i<this.getOrders().getMenuList().size();i++){
				OrderResMenu orm = (OrderResMenu)this.getOrders().getMenuList().get(i);
				if(orm.getMenuName().equals(this.getMenuName())){
					orm.setCopies(orm.getCopies()+1);
					bl=false;
				}
			}
			if(bl){
				menuList = this.getOrders().getMenuList();
				OrderResMenu orm = new OrderResMenu();
				orm.setOrderId(resId);
				orm.setMenuName(menuName);
				orm.setPrice(price);
				orm.setCopies(copies);
				menuList.add(orm);
				this.getOrders().setMenuList(menuList);
			}
		}
		this.getSession().remove(Constant.SHOPPING_SESSION_KEY);
		this.getSession().put(Constant.SHOPPING_SESSION_KEY, this.getOrders());
		if(this.getReturnURL()!=null&&this.getReturnURL().equals("checkOrder")){
			this.setAction("checkOrder");
			return "indexAction";
		}
		return null;
	}
	
	/**
	 * 购物车减
	 * @return
	 */
	public String reduce(){
		if(resId<1 || menuName==null || copies<1 ){
			this.setError("error.error");
			this.setAction("index");
			return null;
		}
		//购物车的东西在session里
		this.setOrders((Orders)this.getSession().get(Constant.SHOPPING_SESSION_KEY));
		
		if(this.getOrders()!=null && this.getOrders().getMenuList()!=null && this.getOrders().getMenuList().size()>0){
			if(this.getOrders().getResId()==this.getResId()){
				for(int i=0;i<this.getOrders().getMenuList().size();i++){
					OrderResMenu orm = (OrderResMenu)this.getOrders().getMenuList().get(i);
					if(orm.getMenuName().equals(this.getMenuName())){
						if(orm.getCopies()>1){
							orm.setCopies(orm.getCopies()-1);
						}else{
							this.getOrders().getMenuList().remove(orm);
						}
					}
				}
			}
			if(this.getOrders().getMenuList().size()==0){
				this.getSession().remove(Constant.SHOPPING_SESSION_KEY);
			}
		}
		if(this.getReturnURL()!=null&&this.getReturnURL().equals("checkOrder")){
			this.setAction("checkOrder");
			return "indexAction";
		}
		return null;
	}
	
	/**
	 * 清空购物车
	 * @return
	 */
	public String remove(){
		//if(this.getId()>0){
//			Orders o = this.getOrdersService().findOrdersByid(this.getId());
//			if(o!=null && o.getState()==-1){
//				this.getOrdersService().removeOrdersById(this.getId());
//				List l = this.getOrderResMenuService().findOrderResMenuByOrderId(this.getId(), "id", Constant.ORDER_ASC);
//				if(l!=null){
//					for(int i=0;i<l.size();i++){
//						OrderResMenu orm = (OrderResMenu)l.get(i);
//						this.getOrderResMenuService().removeOrderResMenuById(orm.getId());
//					}
//				}
//			}
			this.getSession().remove(Constant.SHOPPING_SESSION_KEY);
		//}
		if(this.getReturnURL()!=null&&this.getReturnURL().equals("checkOrder")){
			this.setAction("checkOrder");
			return "indexAction";
		}
		return null;
	}
	
	/**
	 * 清除指定菜
	 * @return
	 */
	public String removeById(){
		if(resId<1 || menuName==null || copies<1 ){
			this.setError("error.error");
			this.setAction("index");
			return null;
		}
		this.setOrders((Orders)this.getSession().get(Constant.SHOPPING_SESSION_KEY));
		if(this.getOrders()!=null && this.getOrders().getMenuList()!=null && this.getOrders().getMenuList().size()>0){
			//判断是否当前店
			if(this.getOrders().getResId()==this.getResId()){
				List newList = new ArrayList();
				for(int i=0;i<this.getOrders().getMenuList().size();i++){
					OrderResMenu orm = (OrderResMenu)this.getOrders().getMenuList().get(i);
					//判断是否当前菜
					if(!orm.getMenuName().equals(this.getMenuName())){
						newList.add(orm);
					}
				}
				this.getOrders().setMenuList(newList);
			}
		}
		if(this.getOrders().getMenuList().size()==0){
			this.getSession().remove(Constant.SHOPPING_SESSION_KEY);
		}
		if(this.getReturnURL()!=null&&this.getReturnURL().equals("checkOrder")){
			this.setAction("checkOrder");
			return "indexAction";
		}
		return null;
	}
}
